﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using ImageUploaderComponent.Data;

namespace ImageUploaderComponent {
    public partial class ImageEditorView : UserControl {
        public ImageEditorView() {
            InitializeComponent();
            
        }

        public Action<bool> FinishedCallback { get; set; }


        private void ButtonClose_Click(object sender, RoutedEventArgs e) {
            Visibility = Visibility.Collapsed;
            FinishedCallback.Invoke(true);
        }
        private FrameworkElement itemHoveredOver;
        private Point pointOfHover;
        private Canvas realRoot;
        private DispatcherTimer timer;
        private bool timerIsRunning = false;
        private Size requestedSize;

        private void textBoxSmallFileNameMouseEnter(object sender, MouseEventArgs e){
            handleMouseEnter(e, sender,Constants.SmallImageSize);
        }

        private void TextBlockLargeFileName_MouseEnter(object sender, MouseEventArgs e) {
            //handleMouseEnter(e,sender,Constants.LargeImageSize);
        }

        private void handleMouseEnter(MouseEventArgs e, object sender, Size requestedSize){
            if (realRoot == null) {
                realRoot = new TreeHelper().FindParentWithName<Canvas>("LayoutCanvas", this);
            }
            this.requestedSize = requestedSize;
            //Set timer to implement hover delay
            if (!timerIsRunning) {
                pointOfHover = e.GetPosition(realRoot);
                timer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 2) };
                timer.Tick += timer_Tick;
                timerIsRunning = true;
                itemHoveredOver = sender as FrameworkElement;
                timer.Start();
            }
        }

        void timer_Tick(object sender, EventArgs e) {
            showImage(sender);
        }

        private void showImage(object state) {
            timer.Stop();
            var data = (ImageDataViewModel)DataContext;
            var helper = new ImageHelper();
            helper.showImage(realRoot, data, pointOfHover, requestedSize);
            timer = null;
        }


        private void TextBoxFileName_MouseLeave(object sender, MouseEventArgs e) {
            if (timerIsRunning) {
                if (timer != null) {
                    timer.Stop();
                }
                timerIsRunning = false;
                itemHoveredOver = null;
            }
        }
    }
}
